package com.web.webtitle.dao;

import com.web.webtitle.entity.Student;
import org.springframework.stereotype.Repository;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Repository//表明这是一个数据仓库
public class HiveDao {
    public List<Student> findAllStudents() throws SQLException {
        ArrayList<Student> students = new ArrayList<>();
        Connection conn= null;
        try {
            conn = null;
            Class.forName("org.apache.hive.jdbc.HiveDriver");
            //获取连接对象
            String url="jdbc:hive2://master:10000/bigdata2";
            conn= DriverManager.getConnection(url,"a","b");//hive的user和password是空，可以任意填写
            //创建语句对象
            Statement statement = conn.createStatement();
            //结果集
            ResultSet resultSet =statement.executeQuery("select * from student");
            while (resultSet.next()){
                Integer id=resultSet.getInt("id");
                String name=resultSet.getString("name");
                String address=resultSet.getString("address");
                Integer age=resultSet.getInt("age");
                //设置值到每个对象中
                Student student = new Student();
                student.setId(id);
                student.setName(name);
                student.setAddress(address);
                student.setAge(age);
                //添加到集合
                students.add(student);
            }
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //关流
            if (Objects.nonNull(conn)){
                conn.close();
            }
        }

       return students;
    }
}
